﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleScale.Forms.Files;
using Janus.Windows.Ribbon;
using VehicleScale.Forms.Vehicles;
using VehicleScale.DataAccess;
using System.Configuration;
using Janus.Windows.ButtonBar;
using VehicleScale.Reports;

namespace VehicleScale
{
    public partial class FrmMDI : Form
    {
        private bool _isCorrectConnection = false;

        #region Singleton Members
        private static volatile FrmMDI instance;
        private static object syncRoot = new Object();

        public static FrmMDI Instance
        {
            get
            {

                //lock (syncRoot)
                //{
                if (instance == null)
                {
                    instance = new FrmMDI();
                }
                //}

                return instance;
            }
        }
        #endregion

        #region Ctors
        private FrmMDI()
        {
            InitializeComponent();
            ICommonDataAccess dataAccess = new CommonDataAccess();

            if (dataAccess.CheckConnection)
            {
                Common.LoadCustomerObject();
                Common.LoadCategoryObject();
                Common.LoadProductObject();

                _isCorrectConnection = true;

                Initialize();
            }
        }
        #endregion

        #region Methods
        public void Initialize()
        {
            this.btnChangePassword.Click += new CommandEventHandler(ClickButtonOpenFile);
            this.btnConfiguration.Click += new CommandEventHandler(ClickButtonOpenFile);
            this.btnLogFile.Click += new CommandEventHandler(ClickButtonOpenFile);
            this.btnExit.Click += new CommandEventHandler(delegate { this.Close(); });
            this.btnLogOut.Click += new CommandEventHandler(delegate
            {
                foreach (var f in this.MdiChildren.Where(c => !c.IsDisposed))
                {
                    f.Close();
                }
                this.OnLoad(null);
            });
            // Click button Open Files
            this.buttonBar1.ItemClick += new Janus.Windows.ButtonBar.ItemEventHandler(buttonBar1_ItemClick);

            this.Size = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

            // Set timer
            Timer timer = new Timer();
            timer.Tick += new EventHandler(delegate
            {
                labelCommand2.Text = DateTime.Now.ToString();
            });
            timer.Start();

            this.buttonBar1.SelectingGroup += new GroupCancelEventHandler(buttonBar1_SelectingGroup);

        }

        void buttonBar1_SelectingGroup(object sender, GroupCancelEventArgs e)
        {
            if (e.Group == buttonBar1.Groups["Group3"])
            {
                this.btnBarCustomerList.Visible = true;
            }
            else
            {
                this.btnBarCustomerList.Visible = false;
            }
        }

        void buttonBar1_ItemClick(object sender, Janus.Windows.ButtonBar.ItemEventArgs e)
        {
            ButtonBar bar = sender as ButtonBar;
            if (bar.SelectedItem != null)
            {
                ButtonBarItem item = bar.SelectedItem as ButtonBarItem;
                switch (item.Key)
                {
                    case "Staff":
                        FrmStaffs.Instance.MdiParent = this;
                        FrmStaffs.Instance.Show();
                        FrmStaffs.Instance.Activate();
                        break;
                    case "Customer":
                        FrmCustomers.Instance.MdiParent = this;
                        FrmCustomers.Instance.Show();
                        FrmCustomers.Instance.Activate();
                        break;
                    case "Category":
                        FrmCategories.Instance.MdiParent = this;
                        FrmCategories.Instance.Show();
                        FrmCategories.Instance.Activate();
                        break;
                    case "Product":
                        FrmProducts.Instance.MdiParent = this;
                        FrmProducts.Instance.Show();
                        FrmProducts.Instance.Activate();
                        break;
                    case "Create":
                        if (btnBarCustomerList.Groups[0].Items.Count < 20)
                        {
                            FrmVehicleScale instance = new FrmVehicleScale();
                            instance.MdiParent = this;
                            instance.Show();
                        }
                        break;
                    case "List":
                        FrmVehicleScaleList.Instance.MdiParent = this;
                        FrmVehicleScaleList.Instance.Show();
                        FrmVehicleScaleList.Instance.Activate();
                        break;
                    case "Report":
                        FrmReport.Instance.MdiParent = this;
                        FrmReport.Instance.Show();
                        FrmReport.Instance.Activate();
                        break;
                }
            }
        }

        #endregion

        #region Events
        void ClickButtonOpenFile(object sender, Janus.Windows.Ribbon.CommandEventArgs e)
        {
            ButtonCommand button = sender as ButtonCommand;
            switch (button.Name)
            {
                case "btnChangePassword":
                    FrmChangePassword.Instance.MdiParent = this;
                    FrmChangePassword.Instance.Show();
                    FrmChangePassword.Instance.Activate();
                    break;
                case "btnConfiguration":
                    FrmConfiguration.Instance.MdiParent = this;
                    FrmConfiguration.Instance.Show();
                    FrmConfiguration.Instance.Activate();
                    break;
                case "btnLogFile":
                    if (TestPass())
                    {
                        FormReadLog.Instance.MdiParent = this;
                        FormReadLog.Instance.Show();
                        FormReadLog.Instance.Activate();
                    }
                    break;

                
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (_isCorrectConnection)
            {
                FrmLogin login = new FrmLogin();
                if (login.ShowDialog() != DialogResult.OK)
                {
                    this.Close();
                    return;
                }

                this.labelCommand3.Text = "Đăng nhập: " + Common.UserLogin.Username;
                try
                {
                    LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Dang nhap Form Main");
                }
                catch
                {
                }
                
                
                // Set permission
                bool IsAdmin = (Common.UserLogin.GroupPermissionID == 1);
                this.btnConfiguration.Visible = IsAdmin;
                this.buttonBar1.Groups["Group1"].Items["Staff"].Visible = IsAdmin;
                //this.buttonBar1.Groups["Group3"].Items["Report"].Visible = IsAdmin;
            }
            else
            {
                Library.Tools.MsgBox.Show("Kết nối cơ sở dữ liệu thất bại!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                FrmConfigDatabase form = new FrmConfigDatabase();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    string connectionStrings = String.Empty;
                    if (form.IsWindowMode)
                    {
                        connectionStrings = String.Format("Data Source={0};Initial Catalog={1};Integrated Security=True;", form.Server, form.Database);
                    }
                    else
                    {
                        connectionStrings = String.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", form.Server, form.Database, form.Username, form.Password);
                    }
                    // Get the application configuration file. 
                    System.Configuration.Configuration config =
                            ConfigurationManager.OpenExeConfiguration(
                            ConfigurationUserLevel.None);

                    // Create a connection string element and 
                    // save it to the configuration file. 

                    // Create a connection string element. 
                    ConnectionStringSettings csSettings =
                            new ConnectionStringSettings("VehicleScale.Properties.Settings.VehicleScaleConnectionString",
                            connectionStrings, "System.Data.SqlClient");

                    // Get the connection strings section. 
                    ConnectionStringsSection csSection =
                        config.ConnectionStrings;

                    // Add the new element. 
                    csSection.ConnectionStrings.Clear();
                    csSection.ConnectionStrings.Add(csSettings);

                    // Save the configuration file. 
                    config.Save(ConfigurationSaveMode.Modified);


                }
                this.Close();

            }
            base.OnLoad(e);
        }

       

        protected override void OnClosed(EventArgs e)
        {
            //instance = null;
            base.OnClosed(e);
        }

        public bool TestPass()
        {
            string pass = String.Empty;
            if (ClassInput.InputBox("Chú ý", "Bạn phải nhập Password de mo Form nay", ref pass) == DialogResult.OK)
            {
                if (pass.ToUpper() != LogFile.passwordFile)
                {
                    Library.Tools.MsgBox.Show("Password không đúng.");
                    return false;                  
                }
                return true;
            }
            else
                return false;
           
        }
        #endregion

    }
}
